package srcInterviewPrep;

public final class StringToLongConverter
{
    /**
     * Converts string to long without using any built in java functions
     * No limitations as such.
     * Handles invalid input, negative values, overflow, etc
     * @param s string to be converted
     * @return converted value in long
     * @throws
     *  IllegalArgumentException: in case of invalid input
     *  RuntimeException: in case of overflow
     */
    public static long StringToLong(String s)
    {
        if (s == null || s.isEmpty())
        {
            throw new IllegalArgumentException("Input String cannot be null or empty");
        }

        int startIndex = 0;
        int sign = 1;

        if (s.charAt(0) == '-')
        {
            sign = -1;
            startIndex = 1;
        }

        long n = 0;

        for (int i = startIndex; i < s.length(); ++i)
        {
            int d = GetDigit(s.charAt(i));

            long n2 = 10*n + d;

            if (n2 < n)
            {
                throw new RuntimeException(
                        String.format(
                                "Overflow ocurred while converting '%s' to long",
                                s));
            }

            n = n2;
        }

        return sign*n;
    }

    private static int GetDigit(char c)
    {
        if (!(c >= 48 && c <= 57))
        {
            throw new IllegalArgumentException(
                String.format(
                    "Character '%s' is not a valid digit",
                    c));
        }

        return c-48;
    }
}
